import React from 'react';
import { observer } from "mobx-react";
import { Row, Col, Button, Modal, message, Switch } from 'antd';
import {
  WeaTools,
  WeaFormItem,
  WeaInput,
  WeaTop,
  WeaBrowser,
  WeaRangePicker,
  WeaSelect,
  WeaScope,
  WeaTable,
  WeaDialog,
  WeaDatePicker,
} from 'ecCom';
import { WeaTableNew } from 'comsMobx';

const style = {
  width: '25%',
  float: 'left',
  marginTop: 8,
  padding: '0 20px'
};

const { WeaTable: WeaTableMobx } = WeaTableNew;

const initState = {
  params: {
    moduleType: '',
    clientType: '',
    status: '',
    url: '',
    userName: '',
    subCompany: '',
    department: '',
    workCode: '',
    startDate: '',
    endDate: '',
    minTime: '',
    maxTime: '',
  },
  userNameDatas: [],
  departmentDatas: [],
  subCompanyDatas: [],
};

const initStateClear = {
  cparams: {
    startDate: '',
    endDate: '',
  },
};

@observer
class PC extends React.Component {
  state = { ...initState, types: [], ...initStateClear, visible: false, status: 'false', switchLoading: false };

  componentDidMount() {
    WeaTools.callApi('/api/systemViewLog/home/GetSystemPageViewType').then(result => {
      this.setState({ types: result.types ? result.types.map(t => ({ key: t.MODULETYPE, showname: t.NAME })) : [] });
    });
    WeaTools.callApi('/api/systemViewLog/home/GetSystemPageViewRecord', 'POST', this.state.params).then(result => {
      const { tableStore } = this.props;
      tableStore.getDatas(result.datas, 1);
    });
    this.setState({ switchLoading: true });
    WeaTools.callApi('/api/systemViewLog/home/GetSystemConfigSwitch').then(result => {
      const { api_status, SystemPageViewTime } = result;
      if (api_status && SystemPageViewTime) {
        this.setState({ status: SystemPageViewTime, switchLoading: false });
      }
    });
  }

  renderDialog = () => {
    const { visible, cparams } = this.state;
    const labels = {
      startDate: '日期之后',
      endDate: '日期之前',
    };
    const items = Object.keys(cparams).map(k => {
      const content = (
        <WeaDatePicker
          value={cparams[k]}
          onChange={v => this.setState({ cparams: { ...cparams, [k]: v } })}
        />
      );
      return (
        <WeaFormItem
          key={k}
          label={labels[k]}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{
            marginTop: 8,
            padding: '0 20px'
          }}
        >
          {content}
        </WeaFormItem>
      );
    });
    let content = '确定要清理：';
    const arr = [];
    if (cparams.startDate) {
      arr.push(`${cparams.startDate} 之后的`);
    }
    if (cparams.endDate) {
      arr.push(`${cparams.endDate} 之前的`);
    }
    if (arr.length === 0) {
      content = '筛选条件为空！确定删除全部数据？';
    } else {
      content += `${arr.join(' ，')}数据？`;
    }
    const buttons = [
      (<Button type="primary" onClick={() => {
        Modal.confirm({
          content,
          onOk: () => {
            WeaTools.callApi('/api/systemViewLog/home/DeleteSystemPageViewRecord', 'POST', this.state.cparams).then(result => {
              if (result.api_status) {
                message.success('清理成功');
                this.setState({ ...initStateClear, visible: false });
                this.componentDidMount();
              } else {
                message.error('清理失败，请重试');
              }
            });
          },
        })
      }}>{arr.length === 0 ? '清理全部数据' : '清理'}</Button>),
      (<Button type="primary" onClick={() => this.setState(initStateClear)}>重置</Button>),
    ]
    return (
      <WeaDialog
        title="清理数据"
        onCancel={()=> this.setState({ visible: false })}
        visible={visible}
        style={{ width: 300, height: 120}}
        buttons={buttons}
      >
        <div style={{ paddingTop: 15 }} >
          {items}
        </div>
      </WeaDialog>
    )
  }

  render() {
    const { tableStore, location: { query: { admin } } } = this.props;
    const { params, types, status, switchLoading } = this.state;
    const labels = {
      moduleType: '模块',
      clientType: '客户端/浏览器版本',
      status: '状态',
      url: '页面地址',
      userName: '用户名',
      subCompany: '分部',
      department: '部门',
      workCode: '工号',
      startDate: '起止日期',
      endDate: '起止日期',
      minTime: '耗时区间',
      maxTime: '耗时区间',
    };
    const options = [{ key: '', showname: '' }].concat(types);
      // { key: '1', showname: '登录至加载出门户' },
      // { key: '2', showname: '第一次新建流程' },
      // { key: '3', showname: '第二次新建流程' },
      // { key: '4', showname: '第一次打开待办流程' },
      // { key: '5', showname: '第二次打开待办流程' },
      // { key: '6', showname: '进入待办流程点击提交或者退回' },
      // { key: '7', showname: '批量提交待办流程' },
      // { key: '8', showname: '查询流程' },
      // { key: '9', showname: '打开一篇发布文档' },
      // { key: '10', showname: '打开会议预定界面' },
      // { key: '11', showname: '会议点击提交至完成' },
      // { key: '12', showname: '编辑一个人员信息' },
      // { key: '13', showname: '查询人员信息' },
      // { key: '14', showname: '流程表单打开' },
    // ];
    const items = Object.keys(params).map(k => {
      let content = (
        <WeaInput
          value={params[k]}
          onChange={v => this.setState({ params: { ...params, [k]: v } })}
          onKeyDown={e => {
            if (e.keyCode && e.keyCode === 13) {
              this.componentDidMount();
              e.preventDefault();
            }
          }}
        />
      );
      if (k === 'moduleType') {
        content = (
          <WeaSelect
            options={options}
            value={params[k]}
            onChange={v => this.setState({ params: { ...params, [k]: v } })}
          />
        );
      }
      if (k === 'userName' || k === 'department' || k === 'subCompany') {
        content = (
          <WeaBrowser
            type={k === 'userName' ? 17 : k === 'subCompany' ? 194 : 57}
            textDecoration={true}
            replaceDatas={this.state[`${k}Datas`]}
            isSingle={false}
            onChange={(ids, names, datas)=> {
              this.setState({
                params: { ...this.state.params , [k]: ids },
                [`${k}Datas`]: datas
              })
            }}
          />
        );
      }
      if (k === 'startDate') {
        content = (
          <WeaRangePicker
            value={[params.startDate, params.endDate]}
            onChange={v => this.setState({
              params: {
                ...params,
                startDate: v[0] || '',
                endDate: v[1] || '',
              }
            })}
          />
        );
      }
      if (k === 'minTime') {
        content = (
          <WeaScope
            isMobx
            value={[params.minTime, params.maxTime]}
            onChange={v => this.setState({
              params: {
                ...params,
                minTime: v[0] || '',
                maxTime: v[1] || '',
              }
            })}
          />
        );
      }
      if (k === 'endDate' || k === 'maxTime') return null;
      return (
        <WeaFormItem
          key={k}
          label={labels[k]}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={style}
        >
          {content}
        </WeaFormItem>
      );
    });
    const btns = [
      <Button type='primary' onClick={() => this.componentDidMount()}>查询</Button>,
      <Button type='primary' onClick={() => this.setState(initState)}>重置</Button>,
      <Button type='primary' onClick={() => tableStore.exportCurrent()}>导出当页数据</Button>,
      <Button type='primary' onClick={() => tableStore.exportAll()}>导出所有数据</Button>,
    ]
    if (admin) {
      btns.push(<Button type='primary' onClick={() => this.setState({ visible: true })}>打开数据清理</Button>);
      btns.push(<span>开启性能检测：</span>);
      btns.push(
        <Switch
          checked={status === 'true'}
          disabled={switchLoading}
          onChange={bool => {
            const newStatus = bool ? 'true' : 'false';
            this.setState({ switchLoading: true, status: newStatus });
            WeaTools.callApi('/api/systemViewLog/home/UpdateSystemConfigSwitch', 'POST', { status: newStatus }).then(result => {
              if (result.api_status) {
                this.setState({ switchLoading: false });
              }
            });
          }}
        />
      );
    }
    return (
      <div>
        <WeaTop
          loading={tableStore.loading}
          icon={<i className="icon-coms-search" />}
          iconBgcolor="#57c5f7"
          title="性能查询"
          buttons={btns}
        />
        <Row style={{ padding: 20 }}>
          <Col span={24}>
            {items}
          </Col>
        </Row>
        <WeaTableMobx comsWeaTableStore={tableStore} needScroll={true} />
        {this.renderDialog()}
      </div>
    );
  }
}

export default PC;